'use strict';

const Controller = require('egg').Controller;

class TravelPlanController extends Controller {
  // GET /api/travel-plans
  async index() {
    const { ctx, service } = this;
    const { userId } = ctx.query;

    // 当传入 userId 时，进行安全校验：必须与 token 中用户一致，或具备管理员权限
    if (userId !== undefined) {
      const token = ctx.request.headers.token || ctx.request.headers.authorization || '';
      const tokenData = service.auth.verifyToken(token);

      if (!tokenData) {
        ctx.status = 401;
        ctx.body = { success: false, message: '未登录或token无效' };
        return;
      }

      // 管理员可查看任意用户；普通用户仅可查看自己的
      if (tokenData.role !== 'admin' && Number(tokenData.userId) !== Number(userId)) {
        ctx.status = 403;
        ctx.body = { success: false, message: '无权限访问该用户数据' };
        return;
      }

      const data = await service.travelPlan.list({ user_id: Number(userId) });
      ctx.body = { success: true, data };
      return;
    }

    // 无 userId 参数时，返回全部（用于社区公开内容与管理端）；具体筛选在前端/其他接口完成
    const data = await service.travelPlan.list();
    ctx.body = { success: true, data };
  }

  // GET /api/travel-plans/:id
  async show() {
    const { ctx, service } = this;
    const id = parseInt(ctx.params.id);
    if (Number.isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: '无效的ID' };
      return;
    }
    const data = await service.travelPlan.getById(id);
    if (!data) {
      ctx.status = 404;
      ctx.body = { success: false, message: '旅行计划不存在' };
      return;
    }
    ctx.body = { success: true, data };
  }

  // POST /api/travel-plans
  async create() {
    const { ctx, service } = this;
    const payload = ctx.request.body || {};

    // 从请求头读取 token（兼容 token/authorization）以获取 userId
    const token = ctx.request.headers.token || ctx.request.headers.authorization || '';
    let tokenData = null;
    try {
      tokenData = await service.auth.verifyToken(token);
    } catch (e) {
      // token 解析失败时允许匿名创建
    }
    const userId = tokenData?.userId ?? null;

    const created = await service.travelPlan.create(payload, userId);
    ctx.body = { success: true, data: created };
  }

  // PUT /api/travel-plans/:id
  async update() {
    const { ctx, service } = this;
    const id = parseInt(ctx.params.id);
    if (Number.isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: '无效的ID' };
      return;
    }
    const payload = ctx.request.body || {};
    const updated = await service.travelPlan.update(id, payload);
    if (!updated) {
      ctx.status = 404;
      ctx.body = { success: false, message: '更新失败，旅行计划不存在' };
      return;
    }
    ctx.body = { success: true, data: updated };
  }

  // DELETE /api/travel-plans/:id
  async destroy() {
    const { ctx, service } = this;
    const id = parseInt(ctx.params.id);
    if (Number.isNaN(id)) {
      ctx.status = 400;
      ctx.body = { success: false, message: '无效的ID' };
      return;
    }
    const ok = await service.travelPlan.remove(id);
    if (!ok) {
      ctx.status = 404;
      ctx.body = { success: false, message: '删除失败，旅行计划不存在' };
      return;
    }
    ctx.body = { success: true, message: '删除成功' };
  }

  /**
   * 审核旅行计划（管理员）
   * PUT /api/travel-plans/:id/audit
   */
  async audit() {
    const { ctx, service } = this;
    const { id } = ctx.params;
    const { token } = ctx.request.headers;
    const { status, reason } = ctx.request.body;

    // 验证token和管理员权限
    const tokenData = service.auth.verifyToken(token);
    if (!tokenData) {
      ctx.body = {
        success: false,
        message: '未登录或token无效'
      };
      return;
    }

    if (tokenData.role !== 'admin') {
      ctx.body = {
        success: false,
        message: '无管理员权限'
      };
      return;
    }

    const result = await service.travelPlan.auditPlan(
      parseInt(id),
      status,
      reason
    );
    ctx.body = result;
  }
}

module.exports = TravelPlanController;